package cn.source.web.controller.zk;

import cn.source.common.core.controller.BaseController;
import cn.source.common.core.domain.AjaxResult;
import cn.source.common.core.page.TableDataInfo;
import cn.source.zk.domain.entity.DevModel;
import cn.source.zk.domain.entity.Device;
import cn.source.zk.service.IZkDevModelService;
import cn.source.zk.service.IZkDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 设备类型相关接口
 */
@RestController
@RequestMapping("/zk/devModel")
@Slf4j
public class ZkDimDevModelController extends BaseController {

    @Autowired
    private IZkDevModelService zkDevModelService;

    @Autowired
    private IZkDeviceService deviceService;

    /**
     * 获取列表信息
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo list(DevModel devModel){
        startPage();
        List<DevModel> list = zkDevModelService.list(devModel);
        return getDataTable(list);
    }

    /**
     * 新增设备类型
     * @param devModel
     * @return
     */
    @PostMapping
    public AjaxResult add(@RequestBody DevModel devModel){
        //检查code编码是否存在
        if (zkDevModelService.checkCodeExist(devModel.getCode(),null)){
            return AjaxResult.error("设备类型"+devModel.getCode()+"已存在,添加失败");
        }

        devModel.setCreateBy(getUsername());
        devModel.setUpdateBy(getUsername());

        return toAjax(zkDevModelService.add(devModel));

    }

    /**
     * 根据id查询设备类型信息
     * @param num
     * @return
     */
    @GetMapping("/{num}")
    public AjaxResult getById(@PathVariable Long num){
        DevModel devModel = zkDevModelService.getById(num);
        return AjaxResult.success(devModel);
    }

    /**
     * 修改设备信息
     * @param devModel
     * @return
     */
    @PutMapping
    public AjaxResult edit(@RequestBody DevModel devModel){
        //检查code编码是否存在
        if (zkDevModelService.checkCodeExist(devModel.getCode(),devModel.getNum())) {
            return AjaxResult.error("设备类型" + devModel.getCode() + "已存在,修改失败");
        }

        devModel.setUpdateBy(getUsername());

        return toAjax(zkDevModelService.edit(devModel));
    }

    /**
     * 删除设备类型
     * @param nums
     * @return
     */
    @DeleteMapping("/{nums}")
    public AjaxResult del(@PathVariable List<Long> nums){
        // 检查设备类型是否被设备使用
        List<Device> devices = deviceService.getByDevModel(nums);
        if (!devices.isEmpty()){
            return  AjaxResult.error("设备类型已被使用，不能删除！");
        }

        log.info("删除的参数:{}",nums);
        return toAjax(zkDevModelService.del(nums));
    }

}
